<?php
namespace app\index\controller;

use think\Db;
use think\Request;
use app\index\model\Article;

class IndexController extends CommonController
{
    protected $model = null;
    //初始化操作
    protected function _initialize()
    {
        parent::_initialize();
        $request = Request::instance();
        //dump($request);
        $this->assign('request',$request);
        //echo '模型:' . $request->module() . '<br/>控制器:' .$request->controller() . '<br>方法' . $request->action();
        //halt('');
        if ($this->model == null) $this->model = new Article();
    }
    //1.前台首页
    public function index()
    {
        $keywords = input('get.keywords');
        if (!empty($keywords)) {
            $list = $this->model->search($keywords);
            //dump($list->total);
        }else {
            //1.取出所有的文章倒序，分页显示
            //$list = Db::name('article')->field('id,title,description,thumb_url,editor,create_time,update_time')->order('id desc')->paginate(8);
            $list = $this->model->article_list();
        }
        $this->assign('keywords', $keywords);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //2.前台栏目页
    public function category($id = 1)
    {
        if ($id) {
            //$lists = Db::name('article')->field('id,title,description,thumb_url,editor,create_time,update_time')->where('category_id', $id)->order('id desc')->paginate(8);
            //$cate = $this->model->cate_list($id);
            // 取出面包屑导航 和 对应栏目下面的所有文章
            $data = $this->model->cate_list($id);
            if (!$data) return $this->error('栏目不存在');

            $this->assign('data', $data);
            return $this->fetch();
        }else {
            return $this->error('栏目不存在');
        }
    }

    //3.文章详情
    public function article($id = 1)
    {
        if ($id) {
            $data = Db::name('article')->where('id', $id)->find();

            $this->assign('data', $data);
            return $this->fetch();
        }else {
            return $this->error('文章不存在');
        }
    }
    //联系我页面
    public function contact()
    {
        return $this->fetch();
    }

    public function increment()
    {
        $input = input('get.');
        if (isset($input['type']) && isset($input['id']) && $input['id'] > 0) {
            switch($input['type']) {
                case 'article' :
                    Db::name('article')->where('id', $input['id'])->setInc('view');
                    break;
            }
        }
        exit(1);
    }
}
